﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
//using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Xml;
using SmartMD.DataAccess.Service;
using SmartMD.DataModel.Entity;
using SmartMD.DataModel;
using System.Windows.Forms;
using SmartMD.Manager.Utils;
using SmartMD.Manager.Container;
using Duoease.ContainerModel.Entity;
using Duoease.ContainerModel;
using Duoease.ContainerModel.Utils;
using Techstar.Dialog;

namespace SmartMD.Manager.Specimens
{
    /// <summary>
    /// Interaction logic for SiteSelectWindow.xaml
    /// </summary>
    public partial class SiteSelectWindow : Window
    {
        private FridgeModel _fridge = null;
        private ShelfModel _shelf = null;
        private BoxModel _box = null;
        //private int _selectedItemIndex;
        private SiteSelectDialog _owner;
        private object _selectedBtn;
        private string _containerName;
        private ContainerModelEntity cme = null;

        public SiteSelectWindow(object sender, SiteSelectDialog owner)
        {           
            InitializeComponent();
            _owner = owner;
            _selectedBtn = sender;
            CM.fridgeClickHandler += new MouseEventHandler(OnFridgeClickHandler);
            CM.shelfClickHandler += new MouseEventHandler(OnShelfClickHandler);

            CM.MsgViewClick += new EventHandler(CM_MsgViewClick);
            CM.MsgGetOutClick += new EventHandler(CM_MsgGetOutClick);
            CM.MsgLoadClick += new EventHandler(CM_MsgLoadClick);
            CM.IsShowContext = false;
        }
        private ObservableCollection<ContainerEntity> _containerEntitys;

        public ObservableCollection<ContainerEntity> ContainerEntitys
        {
            get
            {
                if (_containerEntitys == null)
                {
                    if (SingletonManager.Online)
                    {
                        _containerEntitys = DataServiceManager.ContainerService.GetAllContainers();
                        for (int i = 0; i < _containerEntitys.Count; i++)
                        {
                            _containerEntitys[i].State = RecordState.Normal;

                        }
                        //SingletonManager.Cache.SaveEntity(SingletonManager.TemplatePath, "TemplateType", _templateTypes);
                    }
                    else if (SingletonManager.Cache.ExistsEntity(SingletonManager.TemplatePath, "TemplateType"))
                    {
                        //_containerEntitys = SingletonManager.Cache.LoadEntity<ObservableCollection<ContainerEntity>>(SingletonManager.ContainerPath, "ContainerEntity");
                    }
                    if (_containerEntitys == null)
                        _containerEntitys = new ObservableCollection<ContainerEntity>();
                }
                return _containerEntitys;
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.lbContainer.ItemsSource = ContainerEntitys;

        }
        private void lbContainer_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CM.FridgeModel = null;
            CM.ShelfModel = null;
            CM.BoxModel = null;

            //读取XML画模型
            XmlDocument doc = new XmlDocument();
            ContainerEntity item = (ContainerEntity)this.lbContainer.SelectedItem;
            _containerName = item.SiteCode;

            ContainerModelEntity modelEntity = DataServiceManager.ContainerModelService.GetObjectByName(item.ModelType);
            cme = modelEntity;
            if (modelEntity != null)
            {
                doc.LoadXml(CompressionHelper.DeCompressToString(modelEntity.StyleFile));
            }
            //装入指定的XML文档

            //doc.Load(System.Windows.Forms.Application.StartupPath + "\\bb.xml");
            CM.docmodel.Xml = doc;
            _fridge = CM.ParseXml(modelEntity.ModelType) as FridgeModel;
            _fridge.Name = item.SiteCode;
            CM.FridgeModel = _fridge;

            //冰箱梅格存放容量状态
            int column = _fridge.Column;
            int row = _fridge.Row;
            double[,] percent = new double[row, column];
            List<ContainerEntity> childcontainers = DataServiceManager.ContainerService.GetChildContainers(item.Id);
            if (childcontainers != null)
            {
                string sitecode = null;
                for (int j = 0; j < childcontainers.Count; j++)
                {
                    sitecode = childcontainers[j].SiteCode;
                    string tmp = sitecode.Split('-')[1];
                    int columnno = int.Parse(tmp.Substring(0, 1)) - 1;
                    int rowno = int.Parse(tmp.Substring(1, 1)) - 1;
                    percent[columnno, rowno] = (double)(childcontainers[j].WholeCapacity - childcontainers[j].RemainingCapacity) / (double)childcontainers[j].WholeCapacity;
                }
                CM.IceFullPercent = percent;
            }                
            this.lbContainer.Height = 0;
            this.model.Height = 510;
            CM.IsShowContext = false;            
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            this.lbContainer.Height = 510;
            this.model.Height = 0;
       
            CM.RefreshAllLabel();
        }

        #region 控件事件
        protected void CM_MsgViewClick(object sender, EventArgs e)
        {
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
            SpecimenMsg SM = new SpecimenMsg(SpecimenMsg.SpecimenStyle.GetMsg, CM,cme);
            if (SM.IsShow)
            {
                SM.Show();
            }
        }

        /**
         * 取出标本
         * */
        protected void CM_MsgGetOutClick(object sender, EventArgs e)
        {
            //usingSpecDlg = new UsingSpecDialog();
            //usingSpecDlg.ShowDialog();
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
            SpecimenMsg SM = new SpecimenMsg(SpecimenMsg.SpecimenStyle.RemoveMsg, CM,cme);
            if (SM.IsShow)
            {
                SM.Show();
            }
        }

        protected void CM_MsgLoadClick(object sender, EventArgs e)
        {
            string strPosition = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
            SpecimenMsg SM = new SpecimenMsg(SpecimenMsg.SpecimenStyle.InputMsg, CM,cme);
            SM.Show();
            //System.Windows.MessageBox.Show("打开载入标本窗口,行列号：" + CM.MouseRow + "," + CM.MouseColumn, "提示");
        }
        #endregion

        protected void OnFridgeClickHandler(object sender, MouseEventArgs e)
        {
            //测试架子第1行第2列存放容量状态
            _shelf = CM.ParseXml(ModelStyle.ShelfModel) as ShelfModel;
            if (_shelf == null)
                return;
            int column = _shelf.Column;
            int row = _shelf.Row;
            double[,] percent = new double[row, column];
            List<ContainerEntity> childcontainers = DataServiceManager.ContainerService.GetChildContainersBySitecode(_fridge.Name + CM.SelectedItemID);
            if (childcontainers != null)
            {
                string sitecode = null;
                for (int j = 0; j < childcontainers.Count; j++)
                {
                    sitecode = childcontainers[j].SiteCode;
                    string tmp = sitecode.Split('-')[2];
                    int rowno = int.Parse(tmp.Substring(0, 1)) - 1;
                    int columnno = int.Parse(tmp.Substring(1, 1)) - 1;
                    percent[rowno, columnno] = (double)(childcontainers[j].WholeCapacity - childcontainers[j].RemainingCapacity) / (double)childcontainers[j].WholeCapacity;
                }
                CM.DrawerFullPercent = percent;
            }
        }
        private bool[,] _isFilled = null;
      
        protected void OnShelfClickHandler(object sender, MouseEventArgs e)
        {
            _box = CM.ParseXml(ModelStyle.BoxModel) as BoxModel;
            if (_box != null)
            {
                int column = _box.Column;
                int row = _box.Row;
                _isFilled = new bool[row, column];

                List<ContainerEntity> childcontainers = DataServiceManager.ContainerService.GetChildContainersBySitecode(_fridge.Name + CM.SelectedItemID);
                if (childcontainers != null)
                {
                    string sitecode = null;
                    for (int j = 0; j < childcontainers.Count + this._owner.selectedSitecodeList.Count; j++)
                    {
                        int per = 0;
                        if (j < childcontainers.Count)
                        {
                            sitecode = childcontainers[j].SiteCode;                           
                            per = (childcontainers[j].WholeCapacity - childcontainers[j].RemainingCapacity) / childcontainers[j].WholeCapacity;
                            if (per != 0 && this._owner.sitecodeList.IndexOf(sitecode) < 0)
                            {
                                this._owner.sitecodeList.Add(sitecode);
                            }
                        }
                        else
                        {
                            sitecode = this._owner.selectedSitecodeList[j - childcontainers.Count];
                            per = 1;
                        }
                        string tmp = sitecode.Split('-')[3];
                        int rowno = ModelUtil.GetNumber(tmp.Substring(0, 1)) - 1;
                        int columnno = ModelUtil.GetCodeValue(tmp.Substring(1, 1)) - 1;//int.Parse(tmp.Substring(1, 1)) - 1;
                       
                        _isFilled[rowno, columnno] = (per == 0) ? false : true;
                    }
                    CM.BoxIsFull = _isFilled;
                }
            }
        }

        private void BtnOK_Click(object sender, RoutedEventArgs e)
        {
            _owner._CM = this.CM;
            if (cme != null)
            {
                _owner.ContainerID = cme.Id;
            }
            string selectedId = this.CM.SelectedItemID;
            //(_selectedBtn as System.Windows.Controls.Button).Tag = _containerName + selectedId;
            string sitecode = _containerName + selectedId;
            if (sitecode.Split('-').Length < 4)
            {
                TaskDialogEx.Warning("提示", "请选中未存储的格子！");
                return;
            }
            else
            {
                if (this._owner.sitecodeList.IndexOf(sitecode) >= 0)//已存在
                {
                    TaskDialogEx.Warning("提示", "该格子已存储，请重新选择！");
                    return;
                }
                else
                {
                    (_selectedBtn as System.Windows.Controls.Button).Tag = sitecode;
                    this._owner.selectedSitecodeList.Add(sitecode);
                    this._owner.sitecodeList.Add(sitecode);
                    this.Close();
                }
            }
        }
    }
}
